package com.springmvc.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.springmvc.entry.Bean;
import com.springmvc.entry.ComponentScan;
import com.springmvc.entry.ContextConfig;

public class ParseSpringmvc {
	
	/*
	 * 解析
	 */
	public ContextConfig parseConfig(String path) throws JDOMException, IOException{
		SAXBuilder saxBuilder = new SAXBuilder();
		Document build = saxBuilder.build(path);
		ContextConfig contextConfig = new ContextConfig();
		Element rootElement = build.getRootElement();
		List<Element> children = rootElement.getChildren();
		Element child = rootElement.getChild("annotation-driven");
			if(child!=null){
				String attributeValue = child.getAttributeValue("value");
				contextConfig.setAnnotationDrivenValue(attributeValue);
			}
			for (Element element : children) {
				if(element.getName().equals("component-scan")){
					ComponentScan componentScan = new ComponentScan();
					String basePackage = element.getAttributeValue("base-package");
					String value = element.getAttributeValue("include-sub");
					componentScan.setBasePackage(basePackage);
					componentScan.setincludeSub(value);
					contextConfig.getComponentScanList().add(componentScan);
				}else if(element.getName().equals("bean")){
					Bean bean = new Bean();
					 String className= element.getAttributeValue("class");
					 bean.setClassName(className);
					 List<Element> children2 = element.getChildren();
					 for (Element object : children2) {
						 String name = object.getAttributeValue("name");
						 String value = object.getAttributeValue("value");
						 bean.getProperty().put(name, value);
					}
					 contextConfig.getBeanList().add(bean);
				}
			}
			//children
			return contextConfig;
		}
	public static void main(String[] args) {
		ParseSpringmvc parseSpringmvc = new ParseSpringmvc();
		try {
			//String path = ParseSpringmvc.class.getResource("springmvc.xml").getPath();
			//ContextConfig parseConfig = parseSpringmvc.parseConfig(path);
			//System.out.println(parseConfig);
			URL resource = ParseSpringmvc.class.getClassLoader().getResource("springmvc.xml");
			String path = resource.getPath();
			System.out.println(path);
			ContextConfig parseConfig = parseSpringmvc.parseConfig(path);
			System.out.println(parseConfig.getAnnotationDrivenValue());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
